package cn.tedu.boyou.comment.service.impl;

import cn.tedu.boyou.comment.domain.TravelComment;
import cn.tedu.boyou.comment.repository.ITravelCommentRepository;
import cn.tedu.boyou.comment.service.ITravelCommentService;
import cn.tedu.boyou.common.query.TravelCommentQuery;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

@Service
public class TravelCommentServiceImpl implements ITravelCommentService {

    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private ITravelCommentRepository dao;


    public TravelComment save(TravelComment comment) {
        if(comment.getId()==null){
            comment.setCreateTime(new Date());
        }

        if(comment.getRefComment() != null && StringUtils.hasLength(comment.getRefComment().getId())){
            comment.setRefComment(this.get(comment.getRefComment().getId()));
        }
        TravelComment c = dao.save(comment);
        return c;
    }

    private TravelComment get(String id) {
        return dao.findById(id).get();
    }

    public Page<TravelComment> query(TravelCommentQuery qo) {
        Query query = new Query();
        Criteria criteria = null;
        if(qo.getTravelId() != -1){
            criteria = Criteria.where("travelId").is(qo.getTravelId());
        }else {
            criteria = Criteria.where("travelId").ne(qo.getTravelId());
        }
        /*  if(qo.getKeyword() != null){
            criteria.and("content").regex("^.*"+qo.getKeyword()+".*$");
        }*/
        query.addCriteria(criteria);

        long total = mongoTemplate.count(query, TravelComment.class);
        if(total == 0){
            return Page.empty();
        }

        Pageable pageable = PageRequest.of(qo.getCurrentPage() -1, qo.getPageSize());
        query.with(pageable);
        Sort createTime = Sort.by(Sort.Direction.DESC, "createTime");
        query.with(createTime);
        List<TravelComment> list = mongoTemplate.find(query, TravelComment.class);

        return new PageImpl<TravelComment>(list,pageable,total);
    }

    public List<TravelComment> getCommentByTop5() {
        Query query = new Query();
        query.with(Sort.by(Sort.Direction.DESC,"traveId")).limit(5).skip(0);
        return mongoTemplate.find(query,TravelComment.class);
    }

}
